package com.project.control.imageupload;

import com.project.service.FileUploadService;
import com.project.utils.token.CheckToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("/vue")
@CrossOrigin(origins = "*", methods = {GET, POST}, allowedHeaders = "*", maxAge = 3600)
public class FileUploadController {



    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    private final FileUploadService fileUploadService;

    @Value("${image.path}")
    private String path;

    @Value("${url.path}")
    private String urlPath;

    @Value("${file.path}")
    private String filePath;
    @Autowired
    public FileUploadController(FileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }

    @PostMapping("image")
    @CheckToken
    public Map<String, String> uploadImage(MultipartFile file, HttpServletRequest request) {
        // 这个路径 path 就是工程下 /src/main/webapp/upload，这个路径是发布后才会存在
         // String path = request.getSession().getServletContext().getRealPath("upload");

        logger.info("文件存储路径：{}", path);
        String imageUrl = fileUploadService.upload(file, path);

        //  TinyMCE 要求图片上传后，需要返回一个 json 对象，这个对象必须有 location 属性，此处硬编码
        Map<String, String> map = new HashMap<>();
        map.put("location", urlPath +"/upload/" + imageUrl);
        return map;
    }

    @PostMapping("/upload-content")
    @CheckToken
    public String uploadContent(@RequestBody String content) {
        logger.info("method: uploadContent，上传内容：{}", content);
        // TODO 直接将这部分内容存储到数据库即可，此时 content里的图片已经不是 base64
        return content;
    }

    @PostMapping("upfile")
    @CheckToken
    public Map<String, String> upfile(MultipartFile file, HttpServletRequest request) {
        // 这个路径 path 就是工程下 /src/main/webapp/upload，这个路径是发布后才会存在
        // String path = request.getSession().getServletContext().getRealPath("upload");

        logger.info("文件存储路径：{}", filePath);
        String imageUrl = fileUploadService.upload(file, filePath);

        //  TinyMCE 要求图片上传后，需要返回一个 json 对象，这个对象必须有 location 属性，此处硬编码
        Map<String, String> map = new HashMap<>();
        map.put("location", urlPath +"/upfile/"  + imageUrl);
        return map;
    }
}
